dateEvent = function($)
{

  var userMessages = {}, date = new Date(), year = date.getUTCFullYear(), month = date
      .getUTCMonth() + 1, day = date.getUTCDate(), userData = faceBook
      .getUser(), windowHeight = 0, init = function()
  {
    $('#calendar').fullCalendar(
        {
          editable : false,
          eventBackgroundColor : 'rgba(245, 245, 245, 0.7)',
          eventBorderColor : '#cccccc',
          eventRender : function(event, element)
          {
            if (event.fb_id)
            {
              element.html('<a class="calEvent birthday" id="fbUser'
                  + event.fb_id + '" title="' + event.fb_name + '"><img src="'
                  + event.image + '"/ class="bday-img"><br>' + event.fb_name
                  + '</a>');
            }
            else
            {
              element.html('<a class="calEvent ' + event.type + '" id="'
                  + event.title.replace(/ /g, "_") + '" title="' + event.title
                  + '"><img src="' + event.image + '"/ class="bday-img"><br>'
                  + event.title + '</a>');
            }
          },
          eventClick : function(event, jsEvent, view)
          {
            openDialog(event, jsEvent);
          },
          dayClick : function(date, allDay, jsEvent, view)
          {
            openDialog({
              type : "",
              start : date
            }, jsEvent);
          }
        });

    loadHolidays();

    waitFBReady();
  }, loadHolidays = function()
  {
    $('#calendar').fullCalendar('addEventSource', {
      events : $.parseJSON($("#holidayData").html())
    });
  }, waitFBReady = function()
  {
    if (faceBook.isInitialized())
    {
      genCalData();
    }
    else
    {
      setTimeout(function()
      {
        waitFBReady();
      }, 100);
    }
  }, genCalData = function()
  {
    $.ajax({
      url : "/getMessages",
      type : "get",
      data : {
        accessToken : FB._authResponse.accessToken,
        userid : faceBook.getUser().id
      },
      dataType : "json",
      success : function(data)
      {
        userMessages = data;
      }
    });
    FB.api('/me/friends?fields=name,birthday', function(flist)
    {
      var friends = flist.data;
      var events = new Array();
      for ( var i = 0; i < friends.length; i++)
      {

        if (friends[i].birthday)
        {
          var bdayarr = friends[i].birthday.split('/');
          var thisDate = new Date(year + "/" + bdayarr[0] + "/" + bdayarr[1])
              .getTime();
          var today = new Date(year + "/" + month + "/" + day).getTime();
          var event = {
            fb_id : friends[i].id,
            fb_name : friends[i].name,
            image : 'https://graph.facebook.com/' + friends[i].id + '/picture',
            title : friends[i].name,
            start : (thisDate < today ? year + 1 : year) + '-' + bdayarr[0]
                + '-' + bdayarr[1],
            type : "birthday"
          };
          events.push(event);
        }

      }
      $('#calendar').fullCalendar('addEventSource', {
        events : events
      });

      windowHeight = $("#foxtrotBody").height();
      var obj = new Object;
      obj.height = windowHeight + 50;
      FB.Canvas.setSize(obj);
      FB.Canvas.setAutoGrow(true);

    });
  }, openDialog = function(event, jsEvent)
  {
    $('#msgtabs').dialog({
      minWidth : 600,
      title : 'Post Scheduler - ' + event.start.toLocaleDateString(),
      dialogClass : "dialogWithDropShadow",
      maxHeight : windowHeight - 200,
      modal : true,
      position :
      [ jsEvent.clientX - 150, jsEvent.clientY - 150 ]
    });
    $("#tabs").tabs();
    $('#selectable').selectable();
    var events = $('#calendar').fullCalendar('clientEvents');
    var todayEvents = Array();
    var types = {};
    for ( var i in events)
    {
      if (datesEqual(events[i].start, event.start))
      {
        todayEvents.push(events[i]);
        types[events[i].type] = true;
      }
    }

    var birthdayHtml = '';
    var holidayHtml = '';
    var specialHtml = '';

    $("#tabs").tabs("enable", 0);
    $("#tabs").tabs("enable", 1);
    switch (event.type)
    {
      case "":
        $("#tabs").tabs("select", 2);
      break;
      case "holiday":
        $("#tabs").tabs("select", 1);
      break;
      case "birthday":
        birthdayHtml += '<p>Write a special birthday wish for ' + event.fb_name
            + '. We\'ll send it the day of in case you forget.</p>';
        $("#tabs").tabs("select", 0);
      break;
    }
    if (!types.holiday)
      $("#tabs").tabs("disable", 1);
    if (!types.birthday)
      $("#tabs").tabs("disable", 0);

    birthdayHtml += '<div class="messageActionItems">'
        + '<ul class="birthdayMsgList">';
    holidayHtml += '<div class="messageActionItems">'
        + '<ul class="holidayMsgList">';
    for ( var i in todayEvents)
    {
      switch (todayEvents[i].type)
      {
        case "holiday":
          holidayHtml += getHolidayHtml(todayEvents[i]);
        break;
        case "birthday":
          birthdayHtml += getBirthdayHtml(todayEvents[i]);
        break;
      }
    }

    specialHtml = getSpecialHtml(event.start);

    birthdayHtml += '</ul></div>';
    holidayHtml += '</ul></div>';

    $("#birthdayTab").html(birthdayHtml);
    $("#holidayTab").html(holidayHtml);
    $("#specialTab").html(specialHtml);
    $(".deleteMe").click(killUser);
    $(".createMessageButton").click(showMessage);
    $(".removeMessageButton").click(removeMessage);
    $(".saveMessageButton").click(saveMessage);

    $('.addFriendsButton').click(selectFBUsers);

  }, selectFBUsers = function(jsEvent)
  {

    $(".activeAddFriends").removeClass("activeAddFriends");
    $(this).addClass("activeAddFriends");

    $('#fbfs').dialog({
      minWidth : 750,
      title : 'Find Friends',
      dialogClass : "dialogWithDropShadow",
      position :
      [ jsEvent.clientX - 10, jsEvent.clientY - 100 ],
      close : addUsersToMessage
    });

    $("#findFriends").jfmfs();

  }, addUsersToMessage = function(event, ui)
  {
    var friendSelector = $("#findFriends").data('jfmfs');
    var selectedFriends = friendSelector.getSelectedIds();

    var imageUl = $(".activeAddFriends").parent().find("ul#messageFriends")
        .empty();
    for ( var i in selectedFriends)
    {
      // selected Tab
      imageUl.append(buildFriendLi(selectedFriends[i]));
    }
    $(".deleteMe").click(killUser);
  }, buildFriendLi = function(friendId, isSent)
  {
    return '<li id="'
        + friendId
        + '"><img id="'
        + friendId
        + '" src="https://graph.facebook.com/'
        + friendId
        + '/picture">'
        + (isSent ? ''
            : '<span class="deleteMe ui-icon ui-icon-closethick xbtn clearfix"></span>')
        + '</li>';
  }, killUser = function()
  {
    $(this).parent().remove();
  }, showMessage = function()
  {
    messageUl = $(this).parent();
    if (messageUl.hasClass("specialMsg"))
    {
      messageUl.parent().append(messageUl.clone(true));
      if ($('#msgtabs').height() > windowHeight - 200)
      {
        $('#msgtabs').dialog("option", "height", windowHeight - 200);
      }
      $(this).remove();
    }
    else
      $(this).hide();
    messageUl.find(
        ".saveMessageButton,div#textarea,.addFriendsButton,#messageFriends")
        .show();
    getDefaultMessage(messageUl.find("div#textarea textarea"));
  }, removeMessage = function()
  {
    var self = this;
    var messageUl = $(this).parent();
    $
        .ajax({
          url : "/messageSetter",
          type : "post",
          dataType : "json",
          data : {
            id : messageUl.attr("id"),
            userid : faceBook.getUser().id,
            accessToken : FB._authResponse.accessToken,
            "delete" : "true"
          },
          success : function(data)
          {
            if (data.success)
            {
              faceBookCredits.updateMessageCount();
              $(self).hide();
              messageUl
                  .find(
                      ".saveMessageButton,div#textarea,.addFriendsButton,#messageFriends")
                  .hide();
              messageUl.find("#messageFriends").empty();
              messageUl.find(".createMessageButton").show();
              var textarea = messageUl.find("div#textarea textarea");
              textarea.val("");
              messageUl.attr("id", 0);
            }
            else
            {
              if (data.error)
              {
                alert(data.error);
              }
              else
              {
                alert("Unknown error");
              }
            }
          },
          error : function()
          {
            alert("Unknown error");
          }
        });
    var messageindex = -1;
    for ( var i in userMessages)
    {
      if (userMessages[i].id == messageUl.attr("id"))
      {
        messageindex = i;
      }
    }
    if (messageindex >= 0)
    {
      delete userMessages[messageindex];
    }
  }, saveMessage = function(jsEvent)
  {
    var messageUl = $(this).parent();
    var textarea = messageUl.find("div#textarea textarea");
    var friendid = "";
    if (messageUl.attr("friendId"))
    {
      friendid = messageUl.attr("friendId");
    }
    else
    {
      messageUl.find("ul#messageFriends>li").each(function()
      {
        friendid += this.id + ",";
      });
      friendid = friendid.substr(0, friendid.length - 1);
    }
    if (friendid == "")
    {
      alert("Please choose at least one friend for this message.");
      return;
    }
    var data = {
      id : messageUl.attr("id"),
      date : messageUl.attr("date"),
      month : messageUl.attr("month"),
      year : messageUl.attr("year"),
      holiday : messageUl.attr("holiday"),
      userid : faceBook.getUser().id,
      friendid : friendid,
      type : messageUl.attr("type"),
      accessToken : FB._authResponse.accessToken,
      message : textarea.val()
    };
    $.ajax({
      url : "/messageSetter",
      type : "post",
      data : data,
      dataType : "json",
      success : function(response)
      {
        if (response.success)
        {
          faceBookCredits.updateMessageCount();
          messageUl.find(".removeMessageButton").show();
          messageUl.find("#savedStatus").show().fadeOut(3000);
          var id = messageUl.attr("id");
          id = response.id;
          messageUl.attr("id", id);
          var messageindex = -1;
          for ( var i in userMessages)
          {
            if (userMessages[i].id == id)
            {
              messageindex = i;
            }
          }
          if (messageindex < 0)
          {
            var dateString = data.year + "/" + (parseInt(data.month) + 1) + "/"
                + data.date;
            userMessages.push({
              id : id,
              message : data.message,
              holiday : data.holiday,
              start : new Date(dateString),
              sendDate : dateString,
              type : data.type,
              friendList :
              [ {
                friend : {
                  id : data.friendid
                }
              } ]
            });
          }
          else
          {
            userMessages[messageindex].message = textarea.val();
          }
        }
        else
        {
          if (response.error)
          {
            if (response.error == "buyMessages")
            {
              faceBookCredits.showBuyDialog(jsEvent);
            }
            else
            {
              alert(response.error);
            }
          }
          else
          {
            alert("Unknown error");
          }
        }
      },
      error : function()
      {
        alert("Unknown error");
      }
    });
  }, getBirthdayMessageByFriendId = function(id)
  {
    var message = null;
    for ( var i in userMessages)
    {
      var thisMessage = userMessages[i];
      if (thisMessage.type == "birthday"
          && thisMessage.friendList[0].friend.id == id)
      {
        return thisMessage;
      }
    }
    return message;
  }, getDateAttributes = function(date)
  {
    return 'date="' + date.getUTCDate() + '" month="' + date.getUTCMonth()
        + '" year="' + date.getUTCFullYear() + '"';
  }, getBirthdayHtml = function(event)
  {
    var message = getBirthdayMessageByFriendId(event.fb_id);
    var newMessage = (message == null);
    return '<li><ul id="'
        + (newMessage ? '0' : message.id)
        + '" type="birthday" friendId="'
        + event.fb_id
        + '" '
        + getDateAttributes(event.start)
        + ' class="profileImg birthdayMsg"><li><img src="https://graph.facebook.com/'
        + event.fb_id
        + '/picture"><br><span class="subtleText">'
        + event.fb_name
        +'</span><br></li><div '
        + (newMessage ? 'class="hide" ' : '')
        + ' id="textarea">'
        + '<textarea '
        + (message && message.isSent ? 'disabled ' : '')
        + 'friendName="'
        + event.fb_name
        + '" id="message" type="birthday">'
        + (newMessage ? '' : message.message)
        + '</textarea><span class="hide" id="savedStatus">Message Saved!</span><BR></div>'
        + getButtons(newMessage, message && message.isSent) + '</ul></li>';

  }, getDefaultMessage = function(textArea)
  {
    switch (textArea.attr("type"))
    {
      case "holiday":
        textArea.val('Hope you have a great ' + textArea.attr("eventTitle")
            + '!');
      break;
      case "special":
        textArea.val('Happy Anniversary!');
      break;
      case "birthday":
        textArea.val('Happy birthday ' + textArea.attr("friendName") + '!');
      break;
    }
  }, datesEqual = function(date1, date2)
  {
    return date1.getUTCDate() == date2.getUTCDate()
        && date1.getUTCMonth() == date2.getUTCMonth()
        && date1.getUTCFullYear() == date2.getUTCFullYear();
  }, getMessageByHoliday = function(holidayId)
  {
    var message = null;
    for ( var i in userMessages)
    {
      var thisMessage = userMessages[i];
      if (thisMessage.type == "holiday" && thisMessage.holiday == holidayId)
      {
        return thisMessage;
      }
    }
    return message;
  }, getHolidayHtml = function(event)
  {
    var message = getMessageByHoliday(event.id);
    var newMessage = (message == null);
    var html = '<ul id="' + (newMessage ? '0' : message.id)
        + '" type="holiday" holiday="' + event.id + '" '
        + getDateAttributes(event.start)
        + ' class="profileImg holidayMsg"><p>Wish someone a happy '
        + event.title + '!</p>'
        + getButton("addFriendsButton", newMessage || message.isSent)
        + '<br><ul id="messageFriends">';
    if (!newMessage)
    {
      for ( var j in message.friendList)
      {
        html += buildFriendLi(message.friendList[j].friend.id, message.isSent);
      }
    }
    html += '</ul><div '
        + (newMessage ? 'class="hide" ' : '')
        + 'id="textarea">'
        + '<textarea '
        + (message && message.isSent ? 'disabled ' : '')
        + 'eventTitle="'
        + event.title
        + '" id="message" type="holiday">'
        + (newMessage ? '' : message.message)
        + '</textarea><span class="hide" id="savedStatus">Message Saved!</span><BR>'
        + '<br></div>' + getButtons(newMessage, message && message.isSent)
        + '</ul>';
    return html;
  }, getButtons = function(newMessage, isSent)
  {
    return getButton("saveMessageButton", newMessage || isSent)

    + getButton("createMessageButton", !newMessage || isSent)

    + getButton("removeMessageButton", newMessage || isSent);
  }, getButton = function(type, hidden)
  {
    var icons = {
      createMessageButton : "heart",
      saveMessageButton : "disk",
      removeMessageButton : "closethick",
      addFriendsButton : "person"
    };
    var html = '<button class="'
        + (hidden ? 'hide ' : '')
        + 'button '
        + type
        + ' ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false">'
        + '  <span class="ui-icon ui-icon-';
    html += icons[type];
    html += '"></span>' + '  <span class="ui-button-text">'
        + interpretCamel(type.replace("Button", "")) + '</span>' + '</button>'
    return html;
  }, interpretCamel = function(text)
  {
    var retVal = text[0].toUpperCase();
    for ( var i = 1; i < text.length; i++)
    {
      if (text[i] == text[i].toUpperCase())
        retVal += " ";
      retVal += text[i];
    }
    return retVal;
  }, getSpecialMessagesByDate = function(date)
  {
    var messages = Array();
    for ( var i in userMessages)
    {
      var thisMessage = userMessages[i];
      if (thisMessage.type == "special"
          && datesEqual(new Date(thisMessage.sendDate), date))
      {
        messages.push(thisMessage);
      }
    }
    return messages;
  }, getSpecialHtml = function(start)
  {
    var messages = getSpecialMessagesByDate(start);
    var html = '<p>Create your own special day or occasions'
        + ' and send a note to one or more friends.'
        + ' Even send yourself a reminder in the future!'
        + ' The possibilities are endless when you can schedule your posts.</p>'
        + '<div class="messageActionItems">' + '<ul class="holidayMsgList">';
    for ( var i in messages)
    {
      var message = messages[i];
      html += '<ul id="' + message.id + '" type="special" '
          + getDateAttributes(start) + ' class="profileImg specialMsg">'
          + getButton("addFriendsButton", message.isSent)
          + '<ul id="messageFriends">';
      for ( var j in message.friendList)
      {
        html += buildFriendLi(message.friendList[j].friend.id, message.isSent);
      }
      html += '</ul><div id="textarea">'
          + '<textarea '
          + (message && message.isSent ? 'disabled ' : '')
          + 'id="message" type="special">'
          + message.message
          + '</textarea><span class="hide" id="savedStatus">Message Saved!</span><BR></div>'
          + getButton("saveMessageButton", false || message.isSent)
          + getButton("removeMessageButton", false || message.isSent) + '</ul>';
    }
    html += '<ul id="0" type="special" '
        + getDateAttributes(start)
        + ' class="profileImg specialMsg">'
        + getButton("addFriendsButton", true)
        + '<ul id="messageFriends"></ul><div class="hide" id="textarea"><textarea '
        + (message && message.isSent ? 'disabled ' : '')
        + 'type="special"></textarea><span class="hide" id="savedStatus">Message Saved!</span><BR>'
        + '<br></div>' + getButtons(true) + '</ul></ul></div>';
    return html;

  };

  return {
    init : init
  };
}(jQuery);

$(function()
{
  dateEvent.init();
});
